package com.kyomonn.talkischeap.QuestionBank;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.kyomonn.talkischeap.R;

public class QuestionBankAdapter extends BaseAdapter {
    private final Context context;
    private final int resource;
    private final QuestionBankItem[] questionBankItems;

    public QuestionBankAdapter(Context context, int resource, QuestionBankItem[] questionBankItems) {
        this.context = context;
        this.resource = resource;
        this.questionBankItems = questionBankItems;
    }

    @Override
    public int getCount() {
        return questionBankItems.length;
    }

    @Override
    public Object getItem(int position) {
        return questionBankItems[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 引入 ViewHolder，复用 convertView，避免重复 inflate 和 findViewById，提高滚动流畅性。
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(resource, parent, false);
            holder = new ViewHolder();
            holder.icon = convertView.findViewById(R.id.iv_question_bank_icon);
            holder.name = convertView.findViewById(R.id.tv_question_bank_name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.icon.setImageResource(questionBankItems[position].getIcon());
        holder.name.setText(questionBankItems[position].getName());

        convertView.setOnClickListener(view -> {
            Intent intent = new Intent(context, QuestionPanelActivity.class);
            intent.putExtra("bank_name", questionBankItems[position].getName());
            view.getContext().startActivity(intent);
        });

        return convertView;
    }

    static class ViewHolder {
        ImageView icon;
        TextView name;
    }
}
